<template>
    <n-card class="container flex-container">
        <template #header>
            <n-text>🔍 找到 {{ total }} 条结果</n-text>
        </template>
        <question-answer v-for="item in list" :key="item.id" :answer="item"></question-answer>
        <template v-if="pages > 1" #action>
            <div style="display:flex; justify-content:center; align-items:center;">
                <n-pagination v-model:page="currentPage" :page-count="pages" @update:page="handleCurrentPageChange"/>
            </div>
        </template>
        <n-empty v-if="!list.length" description="什么也没找到" size="huge">
            <template #extra>
                <router-link to="/">
                    <n-button>
                        看看别的
                    </n-button>
                </router-link>
            </template>
        </n-empty>
    </n-card>
</template>

<script setup>
import QuestionAnswer from '../components/QuestionAnswer.vue'
import { onMounted, ref } from 'vue'
import { useQuestionStore } from '../store/question'
import { searchQuestionAnswer } from '../api/search'
import { useRoute } from 'vue-router'
import { useLoadingBar, useMessage } from 'naive-ui'

window.$message = useMessage()

const list = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)
const pages = ref(1)
const questionStore = useQuestionStore()
const route = useRoute()
const loadingBar = useLoadingBar()

const fetchAll = () => {
    loadingBar.start()
    searchQuestionAnswer(currentPage.value, pageSize.value, 'latest', route.params.keyword).then(res => {
        if (res.code === '200') {
            list.value = res.data.records
            total.value = res.data.total
            currentPage.value = res.data.current
            pageSize.value = res.data.size
            pages.value = res.data.pages
            loadingBar.finish()
        }
    })
}

const handleCurrentPageChange = (current) => {
    currentPage.value = current
    fetchAll()
}
onMounted(() => {
        fetchAll()
    },
)

</script>

<style scoped>
.flex-container {
    width: 50%;
}
</style>
